var express = require('express');
var router = express.Router();
var {table_model} = require('../utils/model')
var {aesEncrypt} = require('../utils/index')

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.all('/login',(req,res)=>{
  var query = req.query
  console.log(query);
  table_model.findOne({
    name:query.name,
  })
  .then(result=>{
    if(result){
      //有用户则校验账号密码，成功后登录到首页
      if(result.pass == query.pass){

        res.send("<script>location.href='/';</script>")
      }else{
        res.send(`<script>alert('用户密码不正确');location.href='/login';</script>`)
      }
    }else{
      //没有查询到该用户
        res.send(`<script>alert('当前用户不存在');location.href='/login';</script>`)
    }
  }).catch(err=>{

  res.send("<script>alert('服务器异常');location.href='/register';</script>")
})

})

router.all('/register',(req,res)=>{
  var body = req.body
  console.log(body);
  //插入注册  --先判断是否有这条数据，然后再插入
table_model.findOne({
  name:body.name
}).then(data=>{
  if(data){
    //提示该用户已经注册
    res.send("<script>alert('当前用户已被注册');location.href='/register';</script>")
  }else{
    //没有注册，可以直接注册
    body.time = new Date()
    table_model.insertMany(body).then(result=>{
      res.send(`<script>alert('注册成功，前往登陆');location.href='/login?name=${aesEncrypt(body.name)}';</script>`)
    })
  }

}).catch(err=>{

  res.send("<script>alert('服务器异常');location.href='/register';</script>")
})
})


router.all("/signin",(req,res)=>{
  var body = req.body;
  user_model.findOne({
     ...body
  })
  .then(result=>{
    if(result){
      res.json({
        code:200,
        msg:'登陆成功',
        body,
        result
      })
    }else{
      res.json({
        code:1001,
        msg:'登陆失败',
      })
    }
  })
  .catch(err=>{
    res.json({
      code:500,
      msg:'服务器异常',
      err
    })
  })
 
})


module.exports = router;
